<template>
  <md-page
    title="活动详情"
    isBtn
    :btnTextItems="data.btnTextItems"
    backUrl="/pages/activity/index"
    @btnClick="bottomBtnClick">
    <view class="container">
      <view class="floor1">
        <image class="top_img" mode="widthFix" :src="data.detailInfo?.img"></image>
        <view class="title">{{ data.detailInfo?.title }}</view>
        <view class="status flex-b">
          <viwe v-if="countdown" class="flex-l">
            <view class="m-right-8">
              {{ `${data.detailInfo?.active_state == 1 ? '距离报名开始' : '距离报名结束'}` }}
            </view>
            <!-- 倒计时 -->
            <uni-countdown
              color="#FFFFFF"
              background-color="#007AFF"
              :show-day="countdown?.days > 0"
              :day="countdown?.days"
              :hour="countdown?.hours"
              :minute="countdown?.minutes"
              :second="countdown?.seconds"></uni-countdown>
          </viwe>
          <view v-else>{{ data.detailInfo?.active_state_name }}</view>
          <button class="m-all-0 p-all-0 raidus-lg" open-type="share">
            <md-icon :url="data.configInfo?.share_icon" width="140" height="64" />
            <canvas id="myCanvas" style="display: none"></canvas>
          </button>
        </view>
        <view class="address flex-l">
          <view class="m-right-12"><md-icon name="addr" /></view>
          比赛地点：{{ data.detailInfo?.area }}
        </view>
        <view class="location flex-l">
          <view class="m-right-12"><md-icon name="location" /></view>
          领取参赛包地址：{{ data.detailInfo?.bag_address }}
        </view>
      </view>
      <!-- 流程图 -->
      <view class="floor2">
        <block v-for="(item, index) in data.detailInfo.steps" :key="item.text">
          <view class="item">
            <view class="icon" :style="{ backgroundImage: `url(${item.icon})` }"></view>
            <view class="text">{{ item.text }}</view>
            <view class="date">{{ item.times }}</view>
          </view>
          <view class="arrow flex-c" v-if="index !== data.detailInfo.steps.length - 1">
            <view :class="['image', data.detailInfo.progress_state - 1 === index + 1 ? 'active' : '']"></view>
          </view>
        </block>
      </view>
      <!-- 五个tab -->
      <view class="floor3" v-if="data.currentTabKey">
        <block v-for="item in data.tabs" :key="item.link">
          <view class="item" v-if="data.detailInfo[item.link + '_status'] === 1" @click="() => handleTab(item.link)">
            <image class="icon" :src="item.img"></image>
            <view class="text">{{ item.name }}</view>
          </view>
        </block>
      </view>
      <view class="floor4" v-if="data.currentTabKey">
        <view class="title">{{ data.tabs.find(item => item.link === data.currentTabKey)?.name || '' }}</view>
        <!-- 富文本内容 -->
        <rich-text v-if="data.currentTabKey !== 'kefu'" :nodes="data.detailInfo?.[data.currentTabKey]"></rich-text>
        <view v-if="data.currentTabKey === 'kefu'">
          <Kefu :info="{ ...data.kefu_info, title: data.detailInfo?.title }" />
        </view>
      </view>
    </view>
  </md-page>
  <!-- 参加弹窗 -->
  <uni-popup ref="popup" background-color="#fff">
    <view class="popup-content">
      <!-- 标题栏 -->
      <view class="title">
        <!-- 规则 -->
        <md-icon name="rule" class="rule" @click="handleRule" />
        选择参赛类型
        <!-- 关闭 -->
        <md-icon name="close" class="close" height="25" width="25" @click="handleModalClose" />
      </view>
      <view class="content">
        <view class="btns">
          <view class="m-bottom-42">
            <view
              :style="{
                background: data.configInfo.button_color1 || '#d92121',
                color: data.configInfo.button_color1_text || '#ffffff',
              }"
              class="btn leader"
              @click="() => handleNext('leader')">
              队长报名
            </view>
          </view>
          <view
            :style="{
              background: data.configInfo.button_color3 || '#d92121',
              color: data.configInfo.button_color3_text || '#ffffff',
            }"
            class="btn player"
            @click="() => handleNext('member')">
            队员申请
          </view>
        </view>
      </view>
    </view>
  </uni-popup>
  <!-- 规则弹窗 -->
  <uni-popup ref="rulePopup" background-color="#fff" :mask-click="false">
    <view class="popup-content rule">
      <view class="title">活动免责声明</view>
      <view class="content">
        <!-- 放富文本内容 -->
        <view class="rich-text">
          <rich-text :nodes="data.detailInfo?.know"></rich-text>
        </view>
        <view class="bottom-btn">
          <!-- 勾选协议 -->
          <view class="m-bottom-22">
            <cc-protocolBox
              :agree="data.agree"
              :protocolArr="data.protocolArr"
              @click="data.agree = !data.agree"
              @protocolClick="protocolClick"></cc-protocolBox>
          </view>
          <!-- 确认按钮 -->
          <button
            :style="{
              background: data.configInfo.button_color1 || '#d92121',
              color: data.configInfo.button_color1_text || '#ffffff',
            }"
            :disabled="!data.agree"
            :class="['btn', !data.agree ? 'disabled' : '']"
            @click="handleModalRuleClose">
            请阅读全文并确认
          </button>
        </view>
      </view>
    </view>
  </uni-popup>
  <!-- 发布到组队大厅弹窗 -->
  <uni-popup ref="inputDialog" type="dialog">
    <view class="popup-content publish">
      <view class="publish-title">是否将该活动发布到组队大厅？</view>
      <view class="publish-content">
        <uni-easyinput
          type="textarea"
          v-model="data.remark"
          placeholder="备注：填写一些信息，方便您快速匹配队友"></uni-easyinput>
      </view>
      <view class="publish-bottom-btn">
        <view class="left" @click="() => inputDialog?.close()">取消发布</view>
        <view class="right" @click="dialogInputConfirm">确认发布</view>
      </view>
    </view>
  </uni-popup>
</template>

<script setup lang="ts">
import { reactive, ref } from 'vue';
import { onLoad, onShareAppMessage, onShow } from '@dcloudio/uni-app';
// 组件
import type { BtnTextItem } from '@/components/md-ui/components/md-page/md-page.vue';
import Kefu from '@/pages/activity/components/kefu.vue';
// 接口
import { activeDetail, activeLaunchTeamHall, getActiveKefu, signCheckLogin } from '@/api';
// 工具
import { stringifyParams, Toast } from '@/utils/util';
import moment from 'moment';
import { fromType, UserActiveState } from '@/api/enum';

const data = reactive<any>({
  active_id: -1, // 活动id
  detailInfo: {},
  btnTextItems: [],
  steps: [], // 流程图数据
  tabs: [], // 五个小tab
  currentTabKey: '',
  agree: false, // 是否确认阅读报名协议
  protocolArr: ['《活动免责声明》'],
  remark: '', //
  configInfo: {}, // 全局配置信息
  kefu_info: {}, // 客服信息
});
const popup = ref<any>(null);
const rulePopup = ref<any>(null);
const inputDialog = ref<any>(null);
const modalType = ref<string>('default');
const countdown = ref<Record<string, number>>();
// const tempFilePath = ref('')

const getCountdown = (specificTime: string, flag: boolean) => {
  // 当前时间
  const currentTime = moment();
  // 时间节点
  const specificMoment = moment(specificTime);

  // 距离报名结束时间超过24小时不显示倒计时
  if (flag && specificMoment.diff(currentTime, 'minute') >= 1441) {
    return null;
  }

  // 计算时间差
  const duration = moment.duration(specificMoment.diff(currentTime));
  // 获取小时、分钟和秒的差值
  // Math.abs() 绝对值
  const days = duration.days();
  const hours = duration.hours();
  const minutes = duration.minutes();
  const seconds = duration.seconds();

  // 或者直接输出完整的时间差
  // console.log(`从 ${specificTime} 到现在的时间差: ${days}天 ${hours}小时 ${minutes}分钟 ${seconds}秒`);
  return { days, hours, minutes, seconds };
};

// 点击tab回调
const handleTab = (key: string) => {
  if (key !== 'file') {
    if (key === 'kefu') {
      // 调用接口获取客服信息
      fetchActiveKefu();
    }
    data.currentTabKey = key;
  } else {
    // 下载材料
    uni.navigateTo({
      url: '/pages/activity/files?active_id=' + data.active_id,
    });
  }
};

// 我要参加
const bottomBtnClick = async (info: { item: BtnTextItem }) => {
  const { key } = info.item;

  // 公共的参数
  const commonParams = {
    active_state: data.detailInfo?.active_state,
    template_code: data.detailInfo?.template_code,
    active_id: data.active_id,
    sign_team_id: data.detailInfo?.sign_team_id,
  };
  // 我要参加
  if (key === 'join') {
    // 报名前先判断是否登录过
    const isLogin = await fetchSignCheckLogin();
    if (isLogin) {
      // 个人赛报名
      if (data.detailInfo.template_code != 'team') {
        jumpApplication('leader');
      } else {
        popup.value?.open?.('bottom');
      }
    }
  } else if (key === 'pay') {
    const _params = stringifyParams({
      ...commonParams,
      type: data.detailInfo?.is_header == 1 ? 'leader' : 'member',
      pay: 1,
    });
    // 去支付
    uni.navigateTo({
      url: `/pages/registration/detail?params=${_params}`,
    });
  } else if (key === 'publish') {
    // 发布到组队大厅
    inputDialog.value?.open?.();
  } else if (key === 'detail_leader') {
    // 传递的参数
    const _params = stringifyParams({
      ...commonParams,
      type: 'leader',
    });
    // 查看队长报名详情
    uni.navigateTo({
      url: `/pages/registration/detail?params=${_params}`,
    });
  } else if (key === 'detail_member') {
    // 传递的参数
    const _params = stringifyParams({
      ...commonParams,
      type: 'member',
    });
    // 查看队员报名详情
    uni.navigateTo({
      url: `/pages/registration/detail?params=${_params}`,
    });
  } else if (key === 'match') {
    // 立即比赛
    uni.navigateTo({
      url: '/pages/other/match/map/index?active_id=' + commonParams.active_id,
    });
  } else if (key === 'view_score') {
    // 比赛已结束,且有成绩，跳转至成绩单页面
    Toast('您的成绩为100分');
  } else {
    // 比赛已结束
    Toast('比赛已结束');
  }
};

// 跳转报名页
const jumpApplication = async (modalType: string) => {
  // 传递的参数
  const _params = stringifyParams({
    type: modalType,
    active_id: data.active_id,
    sign_num: data.detailInfo?.sign_num,
    is_houbu: data.detailInfo?.is_houbu,
    is_open_channel: data.detailInfo?.is_open_channel,
    template_code: data.detailInfo?.template_code,
    from: fromType.活动详情,
  });
  uni.navigateTo({
    url: `/pages/registration/index?params=${_params}`,
  });
};

/**
 * 弹窗相关
 */

function handleModalClose() {
  popup.value?.close?.();
}

/**
 * 规则弹窗相关
 */
function handleModalRuleClose() {
  rulePopup.value?.close?.();
  if (modalType.value !== 'default') {
    // 跳转报名页
    jumpApplication(modalType.value);
    // 关闭弹窗
    handleModalClose();
  }
}

const handleRule = () => {
  modalType.value = 'default';
  rulePopup.value?.open?.('center');
};

function protocolClick(tag: string) {
  console.log('点击协议序列 = ' + tag);
}

// 队长 | 队员报名
const handleNext = (type: string) => {
  if (data.agree == false) {
    modalType.value = type;
    rulePopup.value?.open?.('center');
    return;
  }
  // 跳转报名页
  jumpApplication(type);
  handleModalClose();
};

// 发布到组队大厅
function dialogInputConfirm() {
  // data.remark = val;
  fetchActiveLaunchTeamHall();
}

/**
 * 接口相关
 */

// 活动详情
const fetchActiveDetail = async (active_id: number) => {
  data.active_id = active_id;
  uni.showLoading({
    title: '加载中...',
  });
  try {
    const res = await activeDetail({
      active_id,
    });

    // 报名开始前 计算距离报名开始还有多少时间
    if ([1, 2].includes(res.data.active_state)) {
      // 距离活动结束倒计时 active_state = 1
      // 距离报名结束倒计时 active_state = 2
      let date = res.data.active_state == 1 ? res.data.sign_start_time : res.data.sign_end_time;
      const cd = getCountdown(date, res.data.active_state == 2);
      cd && (countdown.value = cd);
    }

    data.detailInfo = res.data;
    // 把活动分享图存到缓存里面
    uni.setStorageSync('shareImg', res.data?.share_img || '');

    const current = data.tabs.find((item: any) => {
      let k = item.link + '_status';
      if (data.detailInfo[k] === 1) return item;
    });
    data.currentTabKey = current ? current.link : '';
    const is_leader = res.data?.is_header == 1; // 队长
    const user_active_state = res.data?.user_active_state; // 用户在当前活动状态
    // 后台控制按钮样式
    let commonStyle = (type: number) => ({
      color: data.configInfo?.['button_color' + type] || '#1CA4C0',
      textColor: data.configInfo?.['button_color' + type + '_text'] || '#ffffff',
    });
    /**
     * 处理页面操作按钮
     */

    /**
     * 组队报名模板
     */
    switch (user_active_state) {
      case UserActiveState.去报名:
        data.btnTextItems = [{ text: '我要参加', key: 'join', ...commonStyle(1) }];
        break;
      case UserActiveState.去支付:
        data.btnTextItems = [{ text: '去支付', key: 'pay', ...commonStyle(1) }];
        break;
      case UserActiveState.查看报名信息且能发布:
        data.btnTextItems = [
          {
            text: '发布到组队大厅',
            key: 'publish',
            ...commonStyle(2),
          },
          {
            text: '查看报名详情',
            key: is_leader ? 'detail_leader' : 'detail_member',
            ...commonStyle(1),
          },
        ];
        break;
      case UserActiveState.查看报名信息:
        data.btnTextItems = [
          {
            text: '查看报名详情',
            key: is_leader ? 'detail_leader' : 'detail_member',
            ...commonStyle(1),
          },
        ];
        break;
      case UserActiveState.开始比赛:
        data.btnTextItems = [{ text: '立即比赛', key: 'match', ...commonStyle(1) }];
        break;
      case UserActiveState.查看证书:
        data.btnTextItems = [{ text: '查看成绩', key: 'view_score', ...commonStyle(1) }];
        break;
    }
    // }
  } catch (error) {}
  uni.hideLoading();
};

// 检查是否登录状态
const fetchSignCheckLogin = async () => {
  try {
    await signCheckLogin();
    return true;
  } catch (error) {}
  return false;
};

// 发布到组队大厅
const fetchActiveLaunchTeamHall = async () => {
  try {
    const res = await activeLaunchTeamHall({
      sign_team_id: data.detailInfo?.sign_team_id,
      remark: data.remark,
    });
    Toast(res?.msg || '添加成功');
  } catch (e) {
    //TODO handle the exception
  }
  inputDialog.value?.close?.();
  data.remark = '';
};

// 获取客服信息
const fetchActiveKefu = async () => {
  try {
    const res = await getActiveKefu({
      active_id: data.active_id,
    });
    data.kefu_info = res.data;
  } catch (error) {}
};

onLoad(option => {
  const configInfo = uni.getStorageSync('configInfo') ? JSON.parse(uni.getStorageSync('configInfo')) : '';
  if (configInfo) {
    data.configInfo = configInfo;
  }
  fetchActiveDetail(option?.active_id);

  // 我的菜单列表
  const activeDetailIcons = uni.getStorageSync('activeDetailIcons')
    ? JSON.parse(uni.getStorageSync('activeDetailIcons'))
    : [];
  data.tabs = activeDetailIcons;

  uni.showShareMenu({
    withShareTicket: true,
    menus: ['shareAppMessage', 'shareTimeline'],
  });
});

onShow(() => {
  if (uni.getStorageSync('isRefresh')) {
    fetchActiveDetail(data?.active_id);
    uni.removeStorageSync('isRefresh');
  }
});

// 分享钩子
onShareAppMessage(res => {
  return {
    title: data.detailInfo?.title || '活动详情',
    // imageUrl: tempFilePath.value,
    // data.detailInfo?.img || data.configInfo?.share_poster,
    path: '/pages/activity/detail?active_id=' + data.active_id,
  };
});
</script>

<style lang="scss" scoped>
.container {
  & > view {
    margin-bottom: 16rpx;
  }
  .raidus-lg {
    &::after {
      border: none;
    }
  }
  .floor1 {
    background: white;
    & > view:not(:last-of-type) {
      margin-bottom: 30rpx;
    }
    padding: 0 40rpx 25rpx;
    font-size: 28rpx;
    color: #333;
    .top_img {
      width: 670rpx;
      height: 364rpx;
    }
    .title {
      font-size: 40rpx;
      margin-top: 30rpx;
    }
    .status {
      color: $danger;
    }
    .location {
      color: #808080;
    }
  }
  .floor2 {
    padding: 40rpx 40rpx 0;
    background: white;
    display: flex;
    align-items: center;
    justify-content: center;
    flex-wrap: wrap;
    color: #b3b3b3;
    .item {
      width: 140rpx;
      display: flex;
      flex-direction: column;
      align-items: center;
      text-align: center;
      margin-bottom: 40rpx;
      .icon {
        width: 60rpx;
        height: 60rpx;
        background-position: center center;
        background-repeat: no-repeat;
        background-size: 100% auto;
        &.active {
          & + .text {
            color: $title;
            font-weight: bold;
          }
        }
      }
    }
    .arrow {
      width: 60rpx;
      height: 60rpx;
      margin: 0 20rpx;
      .image {
        width: 37rpx;
        height: 22rpx;
        background-position: center center;
        background-repeat: no-repeat;
        background-size: 100% auto;
        background-image: url('@/static/images/step_arrow.png');
        &.active {
          background-image: url('@/static/images/step_arrow_a.png');
        }
      }
    }
  }
  .floor3 {
    background: white;
    display: flex;
    align-items: center;
    padding: 30rpx 0 26rpx;
    .item {
      flex: 1;
      display: flex;
      flex-direction: column;
      align-items: center;
      .icon {
        width: 60rpx;
        height: 60rpx;
        margin-bottom: 21rpx;
      }
    }
  }
  .floor4 {
    background: white;
    .title {
      width: 100%;
      height: 88rpx;
      line-height: 88rpx;
      text-align: center;
      color: $title;
      font-size: $fs-34;
    }
  }
}
// 弹窗相关
.popup-content {
  @mixin flex-l-c {
    display: flex;
    flex-direction: column;
    align-items: center;
  }
  @include flex-l-c;
  padding: 15px;
  height: 500rpx;
  background-color: #fff;
  // 发布到组队大厅
  &.publish {
    padding: 0;
    width: calc(680rpx - 30px);
    height: auto;
    border-radius: 20rpx;
    overflow: hidden;
    .publish-title {
      font-size: 34rpx;
      padding: 40rpx 40rpx 0;
      box-sizing: border-box;
    }
    .publish-content {
      width: calc(100% - 80rpx);
      flex: 1;
      margin: 30rpx auto;
      border-radius: 20rpx;
    }
    .publish-bottom-btn {
      height: 88rpx;
      width: 100%;
      display: flex;
      border-top: 1px solid #f9f9f9;
      & > view {
        flex: 1;
        font-size: 34rpx;
        text-align: center;
        height: 88rpx;
        line-height: 88rpx;
      }
      .right {
        border-left: 1px solid #f9f9f9;
        color: #576b95;
      }
    }
  }
  // 须知相关样式
  &.rule {
    width: calc(680rpx - 30px);
    height: 1080rpx;
    .content {
      justify-content: space-between;
      overflow-y: auto;
      .rich-text {
        flex: 1;
        width: 100%;
        overflow-y: auto;
      }
      .bottom-btn {
        width: 100%;
        .btn {
          width: 100%;
          height: 96rpx;
          line-height: 96rpx;
          text-align: center;
          background: $danger;
          border-radius: 20rpx;
          font-size: 34rpx;
          color: #ffffff;
          &.disabled {
            opacity: 0.5;
          }
        }
      }
    }
  }
  .title {
    width: 100%;
    height: 80rpx;
    line-height: 80rpx;
    text-align: center;
    font-size: $fs-34;
    font-weight: bold;
    position: relative;
    .close {
      position: absolute;
      top: 0;
      right: 0;
    }
    .rule {
      position: absolute;
      top: 0;
      left: 0;
    }
  }
  .content {
    width: 100%;
    flex: 1;
    @include flex-l-c;
    justify-content: center;
    .btns {
      text-align: center;
      .btn {
        line-height: 88rpx;
        text-align: center;
        color: white;
        font-size: $fs-34;

        &.leader {
          width: 488rpx;
          height: 88rpx;
          border-radius: 20rpx;
        }

        &.player {
          width: 488rpx;
          height: 88rpx;
          border-radius: 20rpx;
        }
      }
    }
  }
}
</style>
